package com.gqj.elec.controller;

import com.alibaba.fastjson2.JSON;
import com.gqj.common.annotation.Log;
import com.gqj.common.constant.UserConstants;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.enums.BusinessType;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.poi.ExcelUtil;
import com.gqj.elec.domain.ElecMaterial;
import com.gqj.elec.domain.vo.ElecMaterialVo;
import com.gqj.elec.service.IElecMaterialService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物资Controller
 *
 * @author lxq
 * @date 2023-12-17
 */
@RestController
@RequestMapping("/elec/elecMaterial")
public class ElecMaterialController extends BaseController {
    @Autowired
    private IElecMaterialService elecMaterialService;
    @Value("${downloadPath}")
    private String downloadPath;

    /**
     * 查询物资列表
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterial:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElecMaterial elecMaterial) {
        startPage();
        elecMaterial.setDelFlag("0");
        List<ElecMaterial> list = elecMaterialService.selectElecMaterialList(elecMaterial);
        return getDataTable(list);
    }

    /**
     * 查询物资列表
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterial:selectElecMaterialWarehouseList')")
    @GetMapping("/selectElecMaterialWarehouseList")
    public TableDataInfo selectElecMaterialWarehouseList(ElecMaterial elecMaterial) {
        startPage();
        elecMaterial.setDelFlag("0");
        List<ElecMaterial> list = elecMaterialService.selectElecMaterialWarehouseList(elecMaterial);
        return getDataTable(list);
    }

    /**
     * 获取物资详细信息
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterial:query')")
    @GetMapping(value = "/{materialId}")
    public AjaxResult getInfo(@PathVariable("materialId") Long materialId) {
        return AjaxResult.success(elecMaterialService.selectElecMaterialByMaterialId(materialId));
    }

    /**
     * 新增物资
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterial:add')")
    @Log(title = "物资", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElecMaterial elecMaterial) {
        if (UserConstants.NOT_UNIQUE.equals(elecMaterialService.checkMaterialCodeUnique(elecMaterial))) {
            return AjaxResult.error("新增'" + elecMaterial.getMaterialName() + "'失败，编码已存在");
        }
        if (null != elecMaterial.getRfidCode() && !"".equals(elecMaterial.getRfidCode())) {
            if (UserConstants.NOT_UNIQUE.equals(elecMaterialService.checkMaterialRfidUnique(elecMaterial))) {
                return AjaxResult.error("新增'" + elecMaterial.getMaterialName() + "'失败，RFID编码已存在");
            }
        }

        elecMaterial.setCreateBy(getUsername());
        elecMaterial.setMaterialStatus("1");
        return toAjax(elecMaterialService.insertElecMaterial(elecMaterial));
    }

    /**
     * 修改物资
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterial:edit')")
    @Log(title = "物资", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElecMaterial elecMaterial) {
        if (UserConstants.NOT_UNIQUE.equals(elecMaterialService.checkMaterialCodeUnique(elecMaterial))) {
            return AjaxResult.error("修改'" + elecMaterial.getMaterialName() + "'失败，编码已存在");
        }
        if (null != elecMaterial.getRfidCode() && !"".equals(elecMaterial.getRfidCode())) {
            if (UserConstants.NOT_UNIQUE.equals(elecMaterialService.checkMaterialRfidUnique(elecMaterial))) {
                return AjaxResult.error("修改'" + elecMaterial.getMaterialName() + "'失败，RFID编码已存在");
            }
        }
        elecMaterial.setUpdateBy(getUsername());
        return toAjax(elecMaterialService.updateElecMaterial(elecMaterial));
    }

    /**
     * 删除物资
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterial:remove')")
    @Log(title = "物资", businessType = BusinessType.DELETE)
    @DeleteMapping("/{materialIds}")
    public AjaxResult remove(@PathVariable Long[] materialIds) {
        for (Long materialId : materialIds) {
            ElecMaterial elecMaterial = elecMaterialService.selectElecMaterialByMaterialId(materialId);
            if (!UserConstants.MATERIAL_ISDEL.equals(elecMaterial.getMaterialStatus())) {
                return AjaxResult.error("删除工器具'" + elecMaterial.getMaterialName() + "'失败，不是录入状态");
            }
        }
        return toAjax(elecMaterialService.deleteElecMaterialByMaterialIds(materialIds));
    }

    /**
     * 导出物资列表
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterial:export')")
    @Log(title = "物资导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElecMaterial elecMaterial) {
        elecMaterial.setDelFlag("0");
        List<ElecMaterial> list = elecMaterialService.selectElecMaterialList(elecMaterial);
        ExcelUtil<ElecMaterial> util = new ExcelUtil<ElecMaterial>(ElecMaterial.class);
        if (!"3".equals(elecMaterial.getMaterialCategory())) {
            util.hideColumn("sparePartType", "singleWeight", "totalWeight", "number");
        }
        util.exportExcel(response, list, "物资数据");
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<ElecMaterial> util = new ExcelUtil<ElecMaterial>(ElecMaterial.class);
        util.hideColumn("sparePartType", "singleWeight", "totalWeight", "number");
        util.importTemplateExcel(response, "工器具数据");
    }

    @Log(title = "工器具导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('elec:elecMaterial:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, String materialCategory) throws Exception {
        ExcelUtil<ElecMaterial> util = new ExcelUtil<ElecMaterial>(ElecMaterial.class);
        List<ElecMaterial> materialList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        materialCategory = "1";
        String message = elecMaterialService.importMaterial(materialList, updateSupport, operName, materialCategory);
        return AjaxResult.success(message);
    }

    @PostMapping("/importTemplateSpare")
    public void importTemplateSpare(HttpServletResponse response) {
        ExcelUtil<ElecMaterial> util = new ExcelUtil<ElecMaterial>(ElecMaterial.class);
        util.hideColumn("totalWeight", "number", "repairCycle", "rfidCode");
        util.importTemplateExcel(response, "备品备件数据");
    }

    /**
     * 导出物资列表
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterial:spareExport')")
    @Log(title = "备品备件导出", businessType = BusinessType.EXPORT)
    @PostMapping("/spareExport")
    public void spareExport(HttpServletResponse response, ElecMaterial elecMaterial) {
        elecMaterial.setDelFlag("0");
        List<ElecMaterial> list = elecMaterialService.selectElecMaterialList(elecMaterial);
        ExcelUtil<ElecMaterial> util = new ExcelUtil<ElecMaterial>(ElecMaterial.class);
        util.hideColumn("totalWeight", "number", "repairCycle", "rfidCode");
        util.exportExcel(response, list, "物资数据");
    }

    @Log(title = "备品备件导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('elec:elecMaterial:importSpare')")
    @PostMapping("/importDataSpare")
    public AjaxResult importDataSpare(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<ElecMaterial> util = new ExcelUtil<ElecMaterial>(ElecMaterial.class);
        List<ElecMaterial> materialList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = elecMaterialService.importSpare(materialList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/queryStatisticsInfo")
    public AjaxResult queryStatisticsInfo(ElecMaterial elecMaterial) {
        Map<String, Object> sortMap = elecMaterialService.querySortStatistics(elecMaterial);
        Map<String, Object> warehouseMap = elecMaterialService.queryWarehouseStatistics(elecMaterial);
        Map<String, Object> cabinetStatusMap = elecMaterialService.selectMaterialStatusNum();

        Integer[] categoryNum = elecMaterialService.selectCategoryNum(elecMaterial);

        Map<String, Object> statisticsMap = new HashMap();
        statisticsMap.put("sortMap", sortMap);
        statisticsMap.put("warehouseMap", warehouseMap);
        statisticsMap.put("cabinetStatusMap", cabinetStatusMap);
        statisticsMap.put("categoryNum", categoryNum);
        return AjaxResult.success(statisticsMap);
    }

    /**
     * 下载工器具json文件
     */
    @ApiOperation("下载工器具json文件")
    @PreAuthorize("@ss.hasPermi('elec:elecMaterial:downloadJsonElecMaterial')")
    @GetMapping("/downloadJsonElecMaterial")
    public AjaxResult downloadJsonElecMaterial(ElecMaterial elecMaterial) {
        elecMaterial.setDelFlag("0");
        List<ElecMaterial> mt = elecMaterialService.selectElecMaterialList(elecMaterial);
        List<ElecMaterialVo> vos = StorageUtil.copyList(mt, ElecMaterialVo::new);

        String orderNo = "工器具数据" + StorageUtil.getOrderNoTo12();
        String fileName = downloadPath + orderNo + ".json";
        String jsonStringAc = JSON.toJSONString(vos);
        File file = new File(fileName);
        try (FileWriter fileWriter = new FileWriter(file)) {
            fileWriter.write(jsonStringAc);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(fileName);
    }

    /**
     * 查询物资列表-需要检修的
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterial:listRepair')")
    @GetMapping("/listRepair")
    public TableDataInfo listRepair(ElecMaterial elecMaterial) {
        startPage();
        List<ElecMaterial> list = elecMaterialService.listRepair(elecMaterial);
        return getDataTable(list);
    }

    /**
     * 检修物资
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterial:repairUpdate')")
    @PostMapping("/repairMaterial/{materialIds}")
    public AjaxResult repairMaterial(@PathVariable Long[] materialIds) {

        return toAjax(elecMaterialService.repairMaterial(materialIds));
    }

}
